package dao

import (
	"encoding/json"
	"fmt"
	"github.com/go-redis/redis"
	"github.com/jageros/eventhub"
	"log"
	"os/exec"
	"znzc_websocket/configs"
	"znzc_websocket/domain"
)

func OpenRedis() *redis.Client {

	redisInfo := configs.GetRedisInfo()
	log.Println("redis连接信息为：", redisInfo)

	r := Redis(redisInfo)

	RedisClient := redis.NewClient(&redis.Options{
		Addr:     r.Addr,
		Password: r.Password,
		DB:       r.Db,
	})

	return RedisClient

}

//这里的订阅了频道，阻塞了代码继续执行，所以我们 需要 go Subscribe() 来让我们的程序 继续执行 并且go Subscribe() 写在init方法内 服务启动只执行一次
func Subscribe(redisClient *redis.Client) {

	//参数1 频道名 字符串类型
	pub := redisClient.Subscribe("alert")
	_, err := pub.Receive()
	if err != nil {
		return
	}

	checkAlive := configs.GetCheckAlive()

	ch := pub.Channel()

	for msg := range ch {
		log.Println("订阅的频道为：", msg.Channel, "消息内容为：", msg.Payload)
		var s domain.Subscribe
		_ = json.Unmarshal([]byte(msg.Payload), &s)
		s.State = CheckAlive(s.CollectorIp, checkAlive)

		if message, err := json.Marshal(s); err == nil {
			//发布事件id为1的事件用来传递订阅的监控信息
			eventhub.Publish(1, string(message))
		}

	}

}

func Redis(redisInfo map[string]interface{}) *domain.Redis {

	r := new(domain.Redis)

	if value, ok := redisInfo["addr"].(string); ok {
		r.Addr = value
	}

	if value, ok := redisInfo["password"].(string); ok {
		r.Password = value
	}

	if value, ok := redisInfo["db"].(int); ok {
		r.Db = value
	}

	return r

}

func CheckAlive(collectorIp string, checkAlive string) bool {

	//cmd := exec.Command("/bin/sh", "-c", fmt.Sprintf("curl http://%s%s/checkAlive", collectorIp, checkAlive))

	cmd := exec.Command("curl", fmt.Sprintf("http://%s%s/checkAlive", collectorIp, checkAlive))
	fmt.Println(fmt.Sprintf("http://%s%s/checkAlive", collectorIp, checkAlive))
	output, err := cmd.Output()
	if err != nil {
		log.Printf("Execute Shell:%s failed with error:%s", fmt.Sprintf("curl http://%s%s/checkAlive", collectorIp, checkAlive), err.Error())
	}
	//pong := ConvertByte2String(output, "GB18030")
	if string(output) == "服务正常访问!" {
		log.Println("目标服务器", collectorIp, "运行正常！")
		return true
	}
	return false

}
